<template>
  <div class="blog-m-user--login">
    <van-image
      v-if="formType !== 'userInfo'"
      round
      fit="cover"
      width="3rem"
      height="3rem"
      :src="require('@/assets/img/logo.jpeg')"
    />
    <van-uploader v-else :after-read="afterRead">
      <van-image round fit="cover" width="3rem" height="3rem" :src="avatar" />
    </van-uploader>
    <p>{{ formTitle }}</p>
    <MBaseForm ref="formCom" class="blog-m-login--form" :type="formType">
      <div
      v-if="choiceMessage"
        @click="changeType"
        class="blog-route--register"
        v-html="choiceMessage"
      ></div>
    </MBaseForm>
    <div class="blog-m-login--btn">
      <van-button type="info" block @click="subForm">{{
        formType === "userInfo" ? "修改" : formTitle
      }}</van-button>
      <van-button
        v-if="formType === 'userInfo'"
        type="warning"
        block
        @click="logout"
        >退出登录</van-button
      >
    </div>
  </div>
</template>

<script>
/*
  实现用户界面, 
  1. 如果用户已经登录(通过token, 和nickName验证), 走用户信息组件
  2. 如果用户没有登录, 根据路由传递过来的信息, 渲染登录或者注册表单, 

*/
const formMap = {
  login: {
    apiType: "login",
    title: "登录",
    switchMessage: "还没有账号? <span>点击注册</span>",
  },
  register: {
    apiType: "register",
    title: "注册",
    // 使用html标签字符串的方式,添加到view层
    switchMessage: "已经有账号了吗? <span>点击登录</span>",
  },
  userInfo: {
    apiType: "putUserInfo",
    title: "个人信息",
  },
};
import MBaseForm from "@/components/m/MBaseForm";
import FORM_MAP from "@/config/form.config";
import { Notify } from "vant";
import { createNamespacedHelpers } from "vuex";
const { mapState } = createNamespacedHelpers("user");
export default {
  name: "VueEleMUser",
  components: {
    MBaseForm,
  },
  props: {
    state: {
      type: String,
      default: "login",
    },
  },
  data() {
    return {
      avatarData: "",
      stateData: "",
      formCom: null,
      vantFormCom: null,
    };
  },
  computed: {
    choiceMessage() {
      return formMap[this.formType]?.switchMessage || false;
    },
    formTitle() {
      return formMap[this.formType]?.title;
    },
    isLogin() {
      return (this.token && this.userInfo._id) || false;
    },
    formType() {
      return this.isLogin ? "userInfo" : this.stateData || this.state;
    },
    avatar() {
      return this.avatarData || this.userInfo?.avatar;
    },
    apiType() {
      return formMap[this.formType]?.apiType;
    },
    userInfo() {
      return (
        // 将userInfo设置为响应数据, 如果vuex的userInfo改变, 它就改变, 而不需要满足条件时进行methods调用
        Object.fromEntries(
          Object.entries(this.$store.state.user?.userInfo).filter(([key]) => {
            return FORM_MAP["userInfo"].find(
              (item) => key === item.query || false
            );
          })
        ) || {}
      );
    },
    ...mapState(["userInfo", "token"]),
  },
  mounted() {
    this.formCom = this.$refs["formCom"];
    this.vantFormCom = this.$refs["formCom"]?.$refs["blogForm"];
    if (this.formType === "userInfo") {
      this.formCom.form = this.userInfo;
    }
  },
  // watch: {
  //   formType(newValue) {
  //     // 由于会出现登录的异步问题, 所以要监听formType(token, userInfo的变化) 之后修改form的数据

  //   },
  // },
  methods: {
    async afterRead(fileInfo) {
      try {
        let form = new FormData();
        await form.append("file", fileInfo.file);
        let result = await this.$http({ type: "uploadUser", data: form });
        this.avatarData = result.data[0].fileUrl;
      } catch (err) {
        console.log(err);
        Notify({
          type: "danger",
          message: err.message,
        });
      }
    },

    changeType() {
      this.stateData = this.formType === "login" ? "register" : "login";
    },
    subForm() {
      let formData = JSON.parse(JSON.stringify(this.formCom.form));
      this.vantFormCom
        .validate()
        .then(async () => {
          if (this.formType === "userInfo") {
            formData.avatar = this.avatar;
          }
          try {
            let result = await this.$http({
              type: this.apiType,
              data: formData,
            });
            this.formCom.form = {};
            // 这里的userInfo的修改在前端上做的缓存form表单的内容, 对form表单的缓存而已
            if (this.formType === "userInfo") {
              console.log("put");
              await this.$store.dispatch("user/getUserInfo");
              this.formCom.form = this.userInfo;
            }
            Notify({
              message: `${result.message}`,
              type: "success",
            });
          } catch (err) {
            // 这里的错误是请求后服务端报错
            console.log(err);
            Notify({
              message: `${err.response.data.message}`,
              type: "danger",
            });
          }
          // this.resetForm();
        })
        .catch((err) => {
          //这里的错误是前端验证错误
          console.log(err);
        });
      return false;
    },
    logout() {
      this.formCom.form = {};
      this.$store.dispatch("user/logout");
    },
  },
};
</script>
<style lang="stylus" 
>
.blog-m-user--login {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  height: 100%;
  padding: 0 0.5em;
}

.blog-m-login--form {
  width: 100%;
  padding: 0.3em 0;
  background-color: #fff;
}

div.blog-m-login--btn {
  width: 100%;
  margin-bottom: 3.6em;
}
.blog-m-login--btn button:first-child {
  margin-bottom .5em
}

.blog-route--register {
  width: 100%;
  font-size: 12px;
  text-align: right;

  span {
    color: skyblue;
  }
}
</style>